import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { cartAPI } from '@/api/cart'
import type { Cart } from '@/types/cart'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', () => {
    const cartList = ref<Cart[]>([])
    const loading = ref(false)
    const updateLoading = ref(false)

    // 计算购物车商品总数
    const totalItems = computed(() => {
        return cartList.value.reduce((total, cart) => {
            return total + cart.cartItemList.reduce((sum, item) => sum + item.quantity, 0)
        }, 0)
    })

    // 获取购物车列表
    const fetchCartList = async () => {
        if (loading.value) return
        try {
            loading.value = true
            const res = await cartAPI.getCartList()
            if (res.code === 1 && res.data) {
                cartList.value = res.data
            }
        } catch (error) {
            console.error('获取购物车列表失败:', error)
            ElMessage.error('获取购物车列表失败')
        } finally {
            loading.value = false
        }
    }

    // 添加到购物车
    const addToCart = async (bookId: number) => {
        try {
            const res = await cartAPI.addToCart(bookId)
            if (res.code === 1) {
                ElMessage.success('添加到购物车成功')
                await fetchCartList()
                return true
            } else {
                ElMessage.error(res.msg || '添加到购物车失败')
                return false
            }
        } catch (error) {
            console.error('添加到购物车失败:', error)
            ElMessage.error('添加到购物车失败')
            return false
        }
    }

    // 更新购物车商品数量
    const updateCartItem = async (cartId: number, bookId: number, quantity: number) => {
        if (updateLoading.value) return false
        try {
            updateLoading.value = true
            const res = await cartAPI.updateCart({
                user: { userId: cartId },
                book: { bookId },
                quantity
            })
            if (res.code === 1) {
                // 本地更新数据
                const cart = cartList.value.find(c => c.cartId === cartId)
                if (cart) {
                    const item = cart.cartItemList.find(item => item.bookId === bookId)
                    if (item) {
                        item.quantity = quantity
                        // 更新购物车总金额
                        cart.sum = cart.cartItemList.reduce((total, item) => total + item.price * item.quantity, 0)
                    }
                }
                return true
            } else {
                ElMessage.error(res.msg || '更新数量失败')
                return false
            }
        } catch (error) {
            console.error('更新数量失败:', error)
            return false
        } finally {
            updateLoading.value = false
        }
    }

    // 删除购物车商品
    const removeFromCart = async (bookId: number) => {
        try {
            const res = await cartAPI.deleteCartItem(bookId)
            if (res.code === 1) {
                await fetchCartList()
                return true
            } else {
                ElMessage.error(res.msg || '删除失败')
                return false
            }
        } catch (error) {
            console.error('删除失败:', error)
            return false
        }
    }

    // 结算购物车
    const checkout = async (cartId?: number) => {
        try {
            const res = await cartAPI.checkout(cartId)
            if (res.code === 1) {
                await fetchCartList()
                return true
            } else {
                ElMessage.error(res.msg || '结算失败')
                return false
            }
        } catch (error) {
            console.error('结算失败:', error)
            ElMessage.error('结算失败')
            return false
        }
    }

    return {
        cartList,
        loading,
        updateLoading,
        totalItems,
        fetchCartList,
        addToCart,
        updateCartItem,
        removeFromCart,
        checkout
    }
})
